import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { storage } from '@/utils'

export const useThemeStore = defineStore('theme', () => {
  // 状态
  const theme = ref(storage.get('theme') || 'light') // light, dark, auto
  const primaryColor = ref(storage.get('primaryColor') || '#1890ff')
  const fontSize = ref(storage.get('fontSize') || 'medium') // small, medium, large
  const borderRadius = ref(storage.get('borderRadius') || 'medium') // small, medium, large
  const compactMode = ref(storage.get('compactMode') || false)
  const colorWeakness = ref(storage.get('colorWeakness') || false)
  const systemTheme = ref('light')

  // 预设主题色
  const presetColors = [
    { name: '拂晓蓝', value: '#1890ff' },
    { name: '薄暮', value: '#722ed1' },
    { name: '火山', value: '#fa541c' },
    { name: '日暮', value: '#faad14' },
    { name: '明青', value: '#13c2c2' },
    { name: '极光绿', value: '#52c41a' },
    { name: '极客蓝', value: '#2f54eb' },
    { name: '酱紫', value: '#eb2f96' }
  ]

  // 字体大小配置
  const fontSizeConfig = {
    small: {
      base: '12px',
      sm: '13px',
      md: '14px',
      lg: '15px',
      xl: '16px',
      '2xl': '18px',
      '3xl': '20px'
    },
    medium: {
      base: '14px',
      sm: '14px',
      md: '16px',
      lg: '18px',
      xl: '20px',
      '2xl': '22px',
      '3xl': '24px'
    },
    large: {
      base: '16px',
      sm: '16px',
      md: '18px',
      lg: '20px',
      xl: '22px',
      '2xl': '24px',
      '3xl': '28px'
    }
  }

  // 圆角配置
  const borderRadiusConfig = {
    small: {
      sm: '2px',
      md: '4px',
      lg: '6px',
      xl: '8px'
    },
    medium: {
      sm: '4px',
      md: '6px',
      lg: '8px',
      xl: '12px'
    },
    large: {
      sm: '6px',
      md: '8px',
      lg: '12px',
      xl: '16px'
    }
  }

  // 计算属性
  const isDark = computed(() => {
    if (theme.value === 'auto') {
      return systemTheme.value === 'dark'
    }
    return theme.value === 'dark'
  })

  const isLight = computed(() => !isDark.value)

  const currentFontSizes = computed(() => fontSizeConfig[fontSize.value])

  const currentBorderRadius = computed(() => borderRadiusConfig[borderRadius.value])

  const themeClass = computed(() => {
    const classes = []
    
    // 主题类
    classes.push(isDark.value ? 'theme-dark' : 'theme-light')
    
    // 字体大小类
    classes.push(`font-size-${fontSize.value}`)
    
    // 圆角类
    classes.push(`border-radius-${borderRadius.value}`)
    
    // 紧凑模式
    if (compactMode.value) {
      classes.push('compact-mode')
    }
    
    // 色弱模式
    if (colorWeakness.value) {
      classes.push('color-weakness')
    }
    
    return classes.join(' ')
  })

  // CSS 变量
  const cssVariables = computed(() => {
    const variables = {
      '--primary-color': primaryColor.value,
      '--font-size-base': currentFontSizes.value.base,
      '--font-size-sm': currentFontSizes.value.sm,
      '--font-size-md': currentFontSizes.value.md,
      '--font-size-lg': currentFontSizes.value.lg,
      '--font-size-xl': currentFontSizes.value.xl,
      '--font-size-2xl': currentFontSizes.value['2xl'],
      '--font-size-3xl': currentFontSizes.value['3xl'],
      '--border-radius-sm': currentBorderRadius.value.sm,
      '--border-radius-md': currentBorderRadius.value.md,
      '--border-radius-lg': currentBorderRadius.value.lg,
      '--border-radius-xl': currentBorderRadius.value.xl
    }

    // 根据主题添加颜色变量
    if (isDark.value) {
      Object.assign(variables, {
        '--bg-color': '#141414',
        '--bg-color-secondary': '#1f1f1f',
        '--bg-color-tertiary': '#262626',
        '--text-color': '#ffffff',
        '--text-color-secondary': '#a6a6a6',
        '--text-color-tertiary': '#737373',
        '--border-color': '#303030',
        '--border-color-secondary': '#404040',
        '--shadow-color': 'rgba(0, 0, 0, 0.3)'
      })
    } else {
      Object.assign(variables, {
        '--bg-color': '#ffffff',
        '--bg-color-secondary': '#fafafa',
        '--bg-color-tertiary': '#f5f5f5',
        '--text-color': '#000000',
        '--text-color-secondary': '#666666',
        '--text-color-tertiary': '#999999',
        '--border-color': '#d9d9d9',
        '--border-color-secondary': '#f0f0f0',
        '--shadow-color': 'rgba(0, 0, 0, 0.1)'
      })
    }

    return variables
  })

  // 设置主题
  const setTheme = (newTheme) => {
    theme.value = newTheme
    storage.set('theme', newTheme)
    applyTheme()
  }

  // 切换主题
  const toggleTheme = () => {
    if (theme.value === 'light') {
      setTheme('dark')
    } else if (theme.value === 'dark') {
      setTheme('auto')
    } else {
      setTheme('light')
    }
  }

  // 设置主题色
  const setPrimaryColor = (color) => {
    primaryColor.value = color
    storage.set('primaryColor', color)
    applyTheme()
  }

  // 设置字体大小
  const setFontSize = (size) => {
    fontSize.value = size
    storage.set('fontSize', size)
    applyTheme()
  }

  // 设置圆角
  const setBorderRadius = (radius) => {
    borderRadius.value = radius
    storage.set('borderRadius', radius)
    applyTheme()
  }

  // 设置紧凑模式
  const setCompactMode = (compact) => {
    compactMode.value = compact
    storage.set('compactMode', compact)
    applyTheme()
  }

  // 设置色弱模式
  const setColorWeakness = (weakness) => {
    colorWeakness.value = weakness
    storage.set('colorWeakness', weakness)
    applyTheme()
  }

  // 应用主题
  const applyTheme = () => {
    const root = document.documentElement
    
    // 设置主题类
    root.className = root.className.replace(/theme-\w+|font-size-\w+|border-radius-\w+|compact-mode|color-weakness/g, '')
    root.className += ` ${themeClass.value}`
    
    // 设置 CSS 变量
    Object.entries(cssVariables.value).forEach(([key, value]) => {
      root.style.setProperty(key, value)
    })
    
    // 设置 meta theme-color
    const metaThemeColor = document.querySelector('meta[name="theme-color"]')
    if (metaThemeColor) {
      metaThemeColor.setAttribute('content', primaryColor.value)
    }
  }

  // 检测系统主题
  const detectSystemTheme = () => {
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      systemTheme.value = mediaQuery.matches ? 'dark' : 'light'
      
      // 监听系统主题变化
      mediaQuery.addEventListener('change', (e) => {
        systemTheme.value = e.matches ? 'dark' : 'light'
      })
    }
  }

  // 重置主题设置
  const resetTheme = () => {
    theme.value = 'light'
    primaryColor.value = '#1890ff'
    fontSize.value = 'medium'
    borderRadius.value = 'medium'
    compactMode.value = false
    colorWeakness.value = false
    
    // 清除本地存储
    storage.remove('theme')
    storage.remove('primaryColor')
    storage.remove('fontSize')
    storage.remove('borderRadius')
    storage.remove('compactMode')
    storage.remove('colorWeakness')
    
    applyTheme()
  }

  // 获取主题配置
  const getThemeConfig = () => {
    return {
      theme: theme.value,
      primaryColor: primaryColor.value,
      fontSize: fontSize.value,
      borderRadius: borderRadius.value,
      compactMode: compactMode.value,
      colorWeakness: colorWeakness.value
    }
  }

  // 设置主题配置
  const setThemeConfig = (config) => {
    if (config.theme) setTheme(config.theme)
    if (config.primaryColor) setPrimaryColor(config.primaryColor)
    if (config.fontSize) setFontSize(config.fontSize)
    if (config.borderRadius) setBorderRadius(config.borderRadius)
    if (config.compactMode !== undefined) setCompactMode(config.compactMode)
    if (config.colorWeakness !== undefined) setColorWeakness(config.colorWeakness)
  }

  // 初始化主题
  const initTheme = () => {
    detectSystemTheme()
    applyTheme()
  }

  // 监听主题变化
  watch([theme, systemTheme], () => {
    applyTheme()
  })

  return {
    // 状态
    theme,
    primaryColor,
    fontSize,
    borderRadius,
    compactMode,
    colorWeakness,
    systemTheme,
    presetColors,
    fontSizeConfig,
    borderRadiusConfig,
    
    // 计算属性
    isDark,
    isLight,
    currentFontSizes,
    currentBorderRadius,
    themeClass,
    cssVariables,
    
    // 方法
    setTheme,
    toggleTheme,
    setPrimaryColor,
    setFontSize,
    setBorderRadius,
    setCompactMode,
    setColorWeakness,
    applyTheme,
    detectSystemTheme,
    resetTheme,
    getThemeConfig,
    setThemeConfig,
    initTheme
  }
}, {
  persist: {
    key: 'theme-store',
    storage: localStorage,
    paths: ['theme', 'primaryColor', 'fontSize', 'borderRadius', 'compactMode', 'colorWeakness']
  }
})